import { FC, Fragment, useEffect, useState, useMemo } from 'react';
import { captureFrame, FrameData, getVideoDuration } from './captureFrame';
import { Image, Row, Col, Slider, InputNumber } from 'antd';
import type { InputNumberProps } from 'antd';

import { debounce } from 'lodash';
interface propsT {
  videoFile?: File;
  time?: number;
}

const CaptureFrame: FC<propsT> = (props) => {
  const [coverUrl, setCover] = useState('');
  const [videoDuration, setVideoDuration] = useState<number>(0);
  const [time, setTime] = useState<number>(0); //截帧时间
  const minAndMax = useMemo(() => {
    return {
      min: 0,
      max: videoDuration,
    };
  }, [videoDuration]);

  const onChange: InputNumberProps['onChange'] = debounce((newValue) => {
    setTime(newValue as number);
  }, 16.6);

  useEffect(() => {
    const { videoFile } = props;
    if (!videoFile) {
      setCover('');
    } else {
      drawFrame(videoFile, time).then(() => {});
      getDuration(videoFile).then((duration: number) => {
        setVideoDuration(Math.ceil(duration));
      });
    }
  }, [props, time]);
  async function drawFrame(videoFile: File, time: number) {
    let frame = (await captureFrame(videoFile, time)) as FrameData;
    setCover(frame.url);
  }
  async function getDuration(videoFile: File) {
    let duration = (await getVideoDuration(videoFile)) as number;
    return duration;
  }
  return (
    <Fragment>
      {coverUrl ? (
        <Fragment>
          <Image src={coverUrl}></Image>
          <Row>
            <Col span={18}>
              <Slider {...minAndMax} onChange={onChange}></Slider>
            </Col>
            <Col span={2}>
              <InputNumber {...minAndMax} onChange={onChange} value={time}></InputNumber>
            </Col>
          </Row>
        </Fragment>
      ) : (
        `选择视频后生成视频封面`
      )}
    </Fragment>
  );
};

export default CaptureFrame;
